#!/bin/sh

# $Id: rc.firmware 445 2011-05-01 08:48:26Z mkasper $
# part of m0n0wall (http://m0n0.ch/wall)
#
# Copyright (C) 2003-2005 Manuel Kasper <mk@neon1.net>.
# All rights reserved.

CFDEVICE=`cat /var/etc/cfdevice`

if [ $1 != "upgrade" ]; then
	/sbin/umount -f /ftmp > /dev/null 2>&1
	/sbin/mdconfig -d -u 1 > /dev/null 2>&1
fi

case $1 in
enable)
	/sbin/mdmfs -s 16m md1 /ftmp > /dev/null 2>&1
	;;
upgrade)
	# wait 5 seconds before beginning
	sleep 5

	exec </dev/console >/dev/console 2>/dev/console

	echo
	echo "Firmware upgrade in progress..."

	# backup config
	mkdir /tmp/configbak
	cp -p /conf/* /tmp/configbak

	# unmount /cf
	/sbin/umount -f /cf

	# dd image onto card
	if [ -r $2 ]; then
		/usr/bin/gunzip -S "" -c $2 | dd of=/dev/$CFDEVICE ibs=64k obs=64k > /dev/null 2>&1
		echo "Image installed."
	fi

	# mount /cf
	/sbin/mount -w -o noatime /cf

	# restore config
	cp -p /tmp/configbak/* /conf

	# remount /cf ro
	/sbin/umount -f /cf
	/sbin/mount -r /cf

	echo "Done - rebooting system..."

	# unset CGI environment variables so as not to confuse PHP
	unset CONTENT_TYPE GATEWAY_INTERFACE REMOTE_USER REMOTE_ADDR AUTH_TYPE
	unset HTTP_USER_AGENT CONTENT_LENGTH SCRIPT_FILENAME HTTP_HOST
	unset SERVER_SOFTWARE HTTP_REFERER SERVER_PROTOCOL REQUEST_METHOD
	unset SERVER_PORT SCRIPT_NAME SERVER_NAME

	/etc/rc.cleanreboot
	;;
esac
